package com.example.deepseek.controller;

import com.example.deepseek.model.DocumentChunk;
import com.example.deepseek.service.PdfProcessingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/pdf")
@RequiredArgsConstructor
@Slf4j
public class PdfController {

    private final PdfProcessingService pdfProcessingService;

    @PostMapping("/upload")
    public ResponseEntity<Map<String, String>> uploadPdf(@RequestParam("file") MultipartFile file) {
        Map<String, String> response = new HashMap<>();

        if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
            response.put("error", "仅支持PDF文件");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            String result = pdfProcessingService.processPdfDocument(file);
            response.put("status", "success");
            response.put("message", result);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("PDF处理失败", e);
            response.put("error", "PDF处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/search")
    public ResponseEntity<List<DocumentChunk>> searchDocuments(
            @RequestParam("query") String query,
            @RequestParam(value = "max_results", defaultValue = "5") int maxResults) {
        List<DocumentChunk> results = pdfProcessingService.searchRelevantChunks(query, maxResults);
        return ResponseEntity.ok(results);
    }

    @DeleteMapping("/clear")
    public ResponseEntity<Map<String, String>> clearDocuments() {
        Map<String, String> response = new HashMap<>();
        int count = pdfProcessingService.clearAllDocuments();
        response.put("status", "success");
        response.put("message", "成功清除所有文档");
        return ResponseEntity.ok(response);
    }
}